package com.class5.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.class5.springboot.entity.TbXtFile;
import com.class5.springboot.frame.web.SuperRestController;
import com.class5.springboot.frame.web.result.ResultData;
import com.class5.springboot.service.facade.IUploadService;
import com.class5.springboot.util.FileHelper;
import com.class5.springboot.util.StringUtils;
import com.class5.springboot.util.exception.AppException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class UploadFileController extends SuperRestController {

    @Autowired
    private IUploadService uploadService;

    /**
     * @api {POST}  /class5/pub/uploadFile 01.文件上传
     * @apiGroup File
     * @apiDescription  文件上传
     * @apiParamExample 参数说明
     * {
     * 	    file:文件(form-data,MultipartFile),
     * }
     * @apiSuccessExample 成功后返回
     * {
     *     success:true,
     *     content:文件ID
     *  }
     */
    @PostMapping("/pub/uploadFile")
    public ResultData uploadFile(HttpServletRequest request){
        JSONObject param = getBodyObject(request);
        log.info("文件上传测试:{}",param.toString());
        Long fileId = uploadService.uploadFile(request);
        return successWraper(fileId);
    }

    /**
     * @api {POST}  /class5/pub/downLoadFile 02.文件下载
     * @apiGroup File
     * @apiDescription  文件下载
     * @apiParamExample 参数说明
     * {
     * 	    id:文件Id
     * }
     * @apiSuccessExample 成功后返回文
     * {
     *
     * }
     */
    @PostMapping("/pub/downLoadFile")
    public void downLoadFile(HttpServletRequest request,HttpServletResponse response){
        JSONObject param = getBodyObject(request);
        if(StringUtils.isNull(param.getString("id"))){
            throw new AppException("参数不能为空");
        }
        log.info("文件下载测试:{}",param.toString());
        TbXtFile tbXtFile = uploadService.getFileInfo(param);
        try {
            FileHelper.downloadFile(tbXtFile.getFileName(), tbXtFile.getFilePath(),response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
